package com.smz.controller;

import com.smz.dao.TOrderDAO;
import com.smz.entity.TOrder;
import com.smz.service.TOrderService;
import com.smz.service.UserService;
import com.smz.utils.RandomNumber;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;

@Api
@RestController
public class TOrderController {



    @Autowired
    private TOrderService tOrderService;

    @Autowired
    private TOrderDAO tOrderDAO;

    @Autowired
    private UserService userService;


    @ApiOperation("插入订单")
    @PostMapping("tOrder")
    public ResponseEntity<String> addTOrder(@RequestBody TOrder tOrder){
        // 得到当前登录用户
        User userDetail = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //通过用户名查用户id
        com.smz.entity.User user = userService.selectUserByName(userDetail.getUsername());
        int userId = user.getId();
        // 获取随机字符为订单编号
        String orderId = RandomNumber.getItemID(20);
        tOrder.setOrderId(orderId);
        // 获取当前时间为交易时间
        long l = System.currentTimeMillis();
        Timestamp dealTime = new Timestamp(l);
        tOrder.setDealTime(dealTime);
        // 设置交付
        tOrder.setProductId(tOrder.getProductId());
        tOrder.setCustomId(userId);
        tOrder.setNumber(tOrder.getNumber());
        int money = Integer.parseInt(tOrder.getMoney());
        tOrder.setMoney((money * tOrder.getNumber())+"");
        tOrder.setPayType(tOrder.getPayType());
        tOrder.setOrderStatus("已支付");
        tOrder.setPayType("支付宝");
        tOrderService.addTOrder(tOrder);
        return ResponseEntity.ok("ok");
    }
}
